import os
import shutil
from datetime import datetime, timedelta
import asyncio
from ..utils.logger import logger

CACHE_DIR = "cache"
MAX_CACHE_AGE = timedelta(days=7)  # 缓存保留7天
MAX_CACHE_SIZE = 10 * 1024 * 1024 * 1024  # 10GB

async def clean_old_cache():
    """清理过期缓存"""
    try:
        now = datetime.now()
        for file in os.listdir(CACHE_DIR):
            file_path = os.path.join(CACHE_DIR, file)
            file_time = datetime.fromtimestamp(os.path.getmtime(file_path))
            if now - file_time > MAX_CACHE_AGE:
                os.remove(file_path)
                logger.info(f"删除过期缓存: {file}")
    except Exception as e:
        logger.error(f"清理缓存错误: {e}")

async def check_cache_size():
    """检查缓存大小"""
    try:
        total_size = sum(os.path.getsize(os.path.join(CACHE_DIR, f)) 
                        for f in os.listdir(CACHE_DIR))
        if total_size > MAX_CACHE_SIZE:
            # 按修改时间排序，删除最旧的文件
            files = [(f, os.path.getmtime(os.path.join(CACHE_DIR, f))) 
                    for f in os.listdir(CACHE_DIR)]
            files.sort(key=lambda x: x[1])
            
            while total_size > MAX_CACHE_SIZE and files:
                file_name, _ = files.pop(0)
                file_path = os.path.join(CACHE_DIR, file_name)
                file_size = os.path.getsize(file_path)
                os.remove(file_path)
                total_size -= file_size
                logger.info(f"删除超量缓存: {file_name}")
    except Exception as e:
        logger.error(f"检查缓存大小错误: {e}")

async def cache_maintenance():
    """缓存维护任务"""
    while True:
        await clean_old_cache()
        await check_cache_size()
        await asyncio.sleep(3600)  # 每小时检查一次 